import bge

# This script can do model substitution in game mode. 


scene = bge.logic.getCurrentScene()
controller = bge.logic.getCurrentController() 
own = controller.owner
owner = own


if bge.changeModel != None:
	newModel = bge.changeModel
	bge.changeModel = None  
	if newModel.name[0:4] == "Tile":
		if bge.selModel != None:
			# Firs find child of tag holder
			if bge.selModel != "C0":
				curModel = (scene.objects[bge.selModel].children[0])
			else:
				#If it is C0, the first child is the FPS camera, so take second child
				curModel = (scene.objects[bge.selModel].children[1])
			addObj = scene.objects[bge.modelDB[newModel.name]]
			# This model is released from tag
			if curModel.name != addObj.name:
				curModel.removeParent()
				# and kill object
				curModel.endObject()
				#addObj = scene.objects["Printer1"]
				print ("-> Replace %s with %s, for tag %s" %(curModel.name, addObj.name, bge.selModel))
				parObj = scene.objects["Control"]
				newObj = scene.addObject(addObj, parObj)
				if 'init' in newObj:
					newObj['init'] = 1
				newObj.position = scene.objects[bge.selModel].position
				newObj.worldOrientation= scene.objects[bge.selModel].orientation					
				if 'scale' in newObj:
					print ("   * This object has individual scaling")
					newObj.localScale = [newObj['scale'], newObj['scale'], newObj['scale'] ]
				else:
					newObj.localScale = [1,1,1]		 
				newObj.setParent(scene.objects[bge.selModel])
				
			
	